package com.wuyou.configer;

import org.apache.commons.dbcp.BasicDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import javax.sql.DataSource;

/**
 * @author 闵洪友
 * @create 2020-09-02 10:13
 */
@Configuration
@PropertySource(value = "classpath:myconn.properties")
public class MyBatisConfiger {
    @Value("${mydriver}")
    private String mydriver;

    @Value("${myurl}")
    private String url;

    @Value("${myuser}")
    private String username;

    @Value("${mypwd}")
    private String pwd;

    @Bean
    public DataSource dataSource(){
        BasicDataSource ds=new BasicDataSource();
        ds.setDriverClassName(mydriver);
        ds.setUrl(url);
        ds.setUsername(username);
        ds.setPassword(pwd);
        return ds;
    }

    @Bean
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource)throws Exception{
        SqlSessionFactoryBean sf=new SqlSessionFactoryBean();
        sf.setDataSource(dataSource);
        ResourcePatternResolver resolver=new PathMatchingResourcePatternResolver();
        sf.setMapperLocations(resolver.getResources("classpath:mapper/*.xml"));
        return sf.getObject();
    }
}
